from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
from config import config

db = SQLAlchemy()
migrate = Migrate()
jwt = JWTManager()

def create_app(config_name='default'):
    """应用工厂函数"""
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    CORS(app)

    # 保证 JWT 的 subject 始终为字符串，避免误传 int 导致的鉴权错误
    @jwt.user_identity_loader
    def user_identity_lookup(identity):
        try:
            return str(identity)
        except Exception:
            return identity
    
    # 注册蓝图
    from app.controllers import main_bp, decoration_bp, auth_bp
    app.register_blueprint(main_bp)
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    # 调整后端路由前缀以匹配前端 '/api/decoration/*'
    app.register_blueprint(decoration_bp, url_prefix='/api/decoration')
    
    return app
